from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import Group
from .models import CustomUser, CustomGroup


@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    list_display = ('avatar_image', 'email', 'username',
                    'is_active', 'is_staff', 'total_links', 'total_clicks', 'total_domains', 'date_joined')
    list_display_links = ('avatar_image', 'email')
    list_filter = ('is_active', 'is_staff', 'is_superuser',
                   'updated', 'date_joined', 'last_login')
    search_fields = ('email', 'username', 'first_name', 'last_name')
    readonly_fields = ('avatar_image_large', 'change_password',
                       'updated', 'date_joined', 'last_login')
    filter_horizontal = ('user_permissions', 'groups')

    ordering = ('-date_joined',)

    fieldsets = (
        (None, {
            'fields': ('avatar_image_large', 'avatar', 'username', 'email', 'first_name', 'last_name', 'change_password')
        }),
        (_('Permissions & Groups'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')
        }),
        (_('More info'), {
            'fields': ('updated', 'date_joined', 'last_login')
        }),
    )

    add_fieldsets = (
        (None, {
            'fields': ('username', 'email', 'password1', 'password2', 'is_active', 'is_staff', 'is_superuser')
        }),
    )

    def has_change_permission(self, req, obj=None):
        old = super().has_change_permission(req, obj)
        if req.user == obj:
            return True
        return old

    def get_fieldsets(self, req, obj=None):
        original_fieldsets = list(super().get_fieldsets(req, obj))
        if req.user == obj and not req.user.is_superuser:
            # remove the 'Permissions & Groups' section
            del original_fieldsets[1]
            return original_fieldsets
        return original_fieldsets


admin.site.unregister(Group)


@admin.register(CustomGroup)
class GroupAdmin(GroupAdmin):
    pass
